from .models import User
import json
import time
import random
from django.conf import settings
from django.http import JsonResponse
from rest_framework.authtoken.models import Token
from django.core.cache import cache

from .utils import Aliyun

from .serializers import (
    SendSMSCodeSerializer,
    MobileLoginSerializer,
)


def authenticate(request, username=None, password=None):
    try:
        user = User.objects.get(username=username)
        if user.check_password(password):
            return user
        return None
    except:
        return None


def user_login(request):
    if request.method == "POST":
        post_data = json.loads(request.body)
        username = post_data.get('username')
        password = post_data.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            if user.is_active:
                status = 200
                message = 'Login success'
            else:
                status = 405
                message = 'User is not active'
        else:
            status = 405
            message = 'Incorrect username or password'
    else:
        status = 405
        message = 'Get request'
    data = {'message': message}
    return JsonResponse(data, status=status)


def register(request):
    if request.method == "POST":
        post_data = json.loads(request.body)
        # 建立新数据对象但是不写入数据库
        name = post_data.get('name')
        username = post_data.get('username')
        find_user = User.objects.filter(username=username).first()
        if find_user:
            status = 405
            message = 'duplicate username'
            data = {'message': message}
            return JsonResponse(data, status=status)
        password = post_data.get('password')
        sex = 'male' if post_data.get('sex') == '1' else 'female'
        phone_number = post_data.get('phone')
        age = post_data.get('age')
        address = post_data.get('address')
        id_card = post_data.get('id_card')
        allergy_information = post_data.get('allergy')

        add_new_user = User(name=name, username=username, sex=sex, phone_number=phone_number, age=age, address=address,
                            id_card=id_card, allergy_information=allergy_information)
        add_new_user.save_base()
        # 设置密码
        add_new_user.set_password(password)
        # 保存User对象
        add_new_user.save()
        status = 200
        message = 'Register success'
    else:
        status = 405
        message = 'Register failure'
    data = {'message': message}
    return JsonResponse(data, status=status)


def send_sms_code(request, *args, **kwargs):
    post_data = json.loads(request.body)
    serializer = SendSMSCodeSerializer(data=post_data)
    serializer.is_valid()
    error_message = serializer.validated_data.get('error_message', '')
    if error_message:
        return JsonResponse({'message': error_message}, status=405)
    mobile = serializer.validated_data['mobile']
    # 生成随机验证码，发送验证码并将其保存到数据库中
    stored_sms = random.randrange(1000, 9999)
    Aliyun.ali_send_sms(mobile, stored_sms)
    cache.set(mobile, stored_sms, 60)  # 设置mobile:sms键值对，有效期为60s
    return JsonResponse({'message': 'Successfully sent'}, status=200)


def mobile_login(request, *args, **kwargs):
    post_data = json.loads(request.body)
    serializer = MobileLoginSerializer(data=post_data)
    serializer.is_valid()
    error_message = serializer.validated_data.get('error_message', '')
    if error_message:
        return JsonResponse({'message': error_message}, status=405)
    user = serializer.validated_data['user']
    if user:
        message = 'Successfully login'
        status = 200
    else:
        message = 'Login failure'
        status = 405
    return JsonResponse({'message': message}, status=status)